package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"user-mgmt-xy/cache"
	"user-mgmt-xy/models"
	"user-mgmt-xy/pkg"
)

type UserController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (u *UserController) Login() {

	username := u.GetString("username")
	password := u.GetString("password")
	if username == "" || password == "" {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名和密码不能为空",
		}
		u.ServeJSON()
		return
	}
	userLogin := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, userLogin).Int()
	if errCount > 3 {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误3次禁止登录",
		}
		u.ServeJSON()
		return
	}
	var user models.User
	var err error
	err = models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户查询失败",
		}
		u.ServeJSON()
		return
	}
	if user.ID == 0 {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户不存在",
		}
		u.ServeJSON()
		return
	}
	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, userLogin)
		if errCount > 2 {
			cache.Rdb.Set(cache.Ctx, userLogin, 3, time.Hour*2)
			u.Data["json"] = Res{
				Code: 0,
				Msg:  "密码错误3次,封禁2小时",
				Data: nil,
			}
			u.ServeJSON()
			return
		}
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误",
		}
		u.ServeJSON()
		return
	}
	u.Data["json"] = Res{
		Code: 200,
		Msg:  "登录成功",
		Data: user,
	}
	u.ServeJSON()
	return

}
func (u *UserController) List() {

	uid, _ := u.GetInt("uid")
	if uid == 0 {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户Id为空",
		}
		u.ServeJSON()
		return
	}
	var role []models.Role
	err := models.DB.Model(&models.Role{}).Joins("left join user_role_relations on user_role_relations.rid = roles.id").
		Where("user_role_relations.uid = ?", uid).
		Find(&role).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
		}
		u.ServeJSON()
		return
	} else {
		u.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: role,
		}
		u.ServeJSON()
	}
}
func (u *UserController) RoleAdd() {

	role_name := u.GetString("role_name")
	if role_name == "" {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "角色名称为空 ",
		}
		u.ServeJSON()
		return
	}
	data := models.Role{
		RoleName: role_name,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		u.ServeJSON()
		return
	} else {
		u.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
		}
		u.ServeJSON()
	}
}
func (u *UserController) UserAdd() {

	username := u.GetString("username")
	password := u.GetString("password")
	if username == "" || password == "" {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名和密码为空",
		}
		u.ServeJSON()
		return
	}
	rid, _ := u.GetInt("rid")
	if rid == 0 {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "角色ID为空",
		}
		u.ServeJSON()
		return
	}
	data := models.User{
		Username: username,
		Password: pkg.Md5Str(password),
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		u.ServeJSON()
		return
	}
	var user models.User
	err = models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户查询失败",
		}
		u.ServeJSON()
		return
	}
	relationData := models.UserRoleRelation{
		Uid: int(user.ID),
		Rid: rid,
	}
	err = models.DB.Create(&relationData).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		u.ServeJSON()
		return
	}
	u.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
	}
	u.ServeJSON()
	return
}
func (u *UserController) UserList() {

	page, _ := u.GetInt("page", 1)
	size, _ := u.GetInt("size", 3)
	offset := (page - 1) * size
	query := models.DB.Model(&models.User{})
	var count int64
	query.Count(&count)
	var user []models.User
	listKey := "list_ket" + strconv.Itoa(page)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, listKey).Result()
	if cacheList == "" {
		err := query.Offset(offset).Limit(size).Find(&user).Error
		if err != nil {
			u.Data["json"] = Res{
				Code: 0,
				Msg:  "数据查询失败",
			}
			u.ServeJSON()
			return
		}
		cacheData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, listKey, cacheData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheList), &user)
	}
	PageData := make(map[string]interface{})
	PageData["count"] = count
	PageData["user"] = user
	u.Data["json"] = Res{
		Code: 200,
		Msg:  "数据查询成功",
		Data: PageData,
	}
	u.ServeJSON()
	return

}
func (u *UserController) UserDel() {

	id, _ := u.GetInt("id")
	userDel := "user_del" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, userDel).Result()
	if cacheData == "" {
		err := models.DB.Where("id=?", id).Delete(&models.User{}).Error
		if err != nil {
			u.Data["json"] = Res{
				Code: 0,
				Msg:  "删除失败",
			}
			u.ServeJSON()
			return
		}
		cachedata, _ := json.Marshal(&models.User{})
		cache.Rdb.Set(cache.Ctx, userDel, cachedata, time.Hour*2)
	} else {

		json.Unmarshal([]byte(cacheData), &models.User{})
	}
	u.Data["json"] = Res{
		Code: 200,
		Msg:  "删除成功",
	}
	u.ServeJSON()
}
